#include <iostream>
#include <vector>
#include <pthread.h>
#include <time.h>
#include <unistd.h>

const int N1 = 5;
const int N2 = 5;

int share_data = 1;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

void* Reader(void* args)
{
    int* num = static_cast<int*>(args);
    while (true)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("reader thread-%d[%ld]read data: %d\n", *num, pthread_self(),share_data);
        sleep(1);  // 模拟读取数据
        pthread_rwlock_unlock(&rwlock);
    }
    delete num;
    return nullptr;
}

void* Writer(void* args)
{
    int* num = static_cast<int*>(args);
    while (true)
    {
        pthread_rwlock_wrlock(&rwlock);
        int data = rand() % 100;
        share_data = data;
        printf("writer thread-%d[%ld]write data: %d\n", *num, pthread_self(), data  );
        sleep(1); // 模拟写入数据
        pthread_rwlock_unlock(&rwlock);
    }
    delete num;
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    std::vector<pthread_t> v;
    for (int i = 0; i < N1; i++)
    {
        int* num = new int(i + 1);
        pthread_t tid;
        pthread_create(&tid, nullptr, Reader, (void*)num);
        v.push_back(tid);
    }

    for (int i = 0; i < N2; i++)
    {
        int* num = new int(i + 1);
        pthread_t tid;
        pthread_create(&tid, nullptr, Writer, (void*)num);
        v.push_back(tid);
    }

    for (const auto& e : v)
    {
        pthread_join(e, nullptr);
    }
    return 0;
}